package com.android.hedgehog;

import java.io.FileNotFoundException;
import java.net.URL;
import java.net.URLConnection;

import com.scoreloop.client.android.core.addon.AndroidImage;
import com.scoreloop.client.android.core.controller.RequestController;
import com.scoreloop.client.android.core.controller.RequestControllerException;
import com.scoreloop.client.android.core.controller.RequestControllerObserver;
import com.scoreloop.client.android.core.controller.TermsOfServiceController;
import com.scoreloop.client.android.core.controller.UserController;
import com.scoreloop.client.android.core.model.Continuation;
import com.scoreloop.client.android.core.model.Image;
import com.scoreloop.client.android.core.model.Session;
import com.scoreloop.client.android.core.model.TermsOfService;
import com.scoreloop.client.android.core.model.TermsOfService.Status;
import com.scoreloop.client.android.core.model.User;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;

public class ProfileActivity extends Activity {

	private final static int DIALOG_PROGRESS = 0;
	private final static int DIALOG_SUCCESS = 1;
	private final static int DIALOG_ERROR = 2;

	// Intent constant
	private final static int INTENT_PICK_PICTURE = 0;

	private User user;

	private EditText usernameText;
	private EditText emailText;
	

	// saves the last error occurred, so we can read it in onPrepareDialog()
	String dialogErrorMsg = "";
	String dialogSuccessMsg = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.profile2);

		TermsOfService tos = Session.getCurrentSession().getUsersTermsOfService();
		if(tos.getStatus()!=Status.ACCEPTED){
			
		}
		Log.d("------------", "1111111111111");

		// GET CURRENT USER
		user = Session.getCurrentSession().getUser();

		usernameText = (EditText) findViewById(R.id.etUsername);
		emailText = (EditText) findViewById(R.id.etEmail);

		
		// SAVE BUTTON
		((Button)findViewById(R.id.bSave)).setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				

				// user should enter email
				if (emailText.getText().length() < 6) {
					dialogErrorMsg = "improper email";
					showDialog(DIALOG_ERROR);
					return;
				}

				// UPDATE USER VALUES
				user.setLogin(usernameText.getText().toString());
				user.setEmailAddress(emailText.getText().toString());

				// SET UP A REQUEST OBSERVER ( UPDATING THE SERVER)
				RequestControllerObserver observer = new RequestControllerObserver() {

					public void requestControllerDidReceiveResponse(
							RequestController arg0) {

						dismissDialog(DIALOG_PROGRESS);
						dialogSuccessMsg = "profile success string";
						showDialog(DIALOG_SUCCESS);

					}

					public void requestControllerDidFail(
							RequestController controller, Exception exception) {
						dismissDialog(DIALOG_PROGRESS);

						// Error handling has to account for many different
						// types of failures...
						if (exception instanceof RequestControllerException) {

							RequestControllerException ctrlException = (RequestControllerException) exception;

							if (ctrlException
									.hasDetail(RequestControllerException.DETAIL_USER_UPDATE_REQUEST_EMAIL_TAKEN)) {
								// Rare success scenario
								dialogSuccessMsg = "profile success email taken string";
								showDialog(DIALOG_SUCCESS);
							} else {

								dialogErrorMsg = "";

								// email may be invalid
								if (ctrlException
										.hasDetail(RequestControllerException.DETAIL_USER_UPDATE_REQUEST_INVALID_EMAIL)) {
									dialogErrorMsg += "profile_error_email_invalid string";
								}
								// username may be invalid
								if (ctrlException
										.hasDetail(RequestControllerException.DETAIL_USER_UPDATE_REQUEST_USERNAME_TAKEN)) {
									dialogErrorMsg += "Username already taken. ";
								} else if (ctrlException
										.hasDetail(RequestControllerException.DETAIL_USER_UPDATE_REQUEST_USERNAME_TOO_SHORT)) {
									dialogErrorMsg += "Username tooo short.";
								} else if (ctrlException
										.hasDetail(RequestControllerException.DETAIL_USER_UPDATE_REQUEST_INVALID_USERNAME)) {
									dialogErrorMsg += "Not a proper username. ";
								}
								showDialog(DIALOG_ERROR);

							}

						} else {// generic exception
							dialogErrorMsg = exception.getLocalizedMessage();
							showDialog(DIALOG_ERROR);
						}
						// update displayed values
						User user = ((UserController) controller).getUser();
						usernameText.setText(user.getLogin());
						emailText.setText(user.getEmailAddress());

					}// requestControllerDidFail

				};

				// with our observer, set up the request controller
				UserController userController = new UserController(observer);

				// pass the user into the controller
				userController.setUser(user);

				showDialog(DIALOG_PROGRESS);

				// submit our changes
				userController.submitUser();

			}// ONCLICK
		});// SETONCLICK

		Log.d("------------", "2222222222222222222");
		// click listener for "picture" button
		((ImageButton)findViewById(R.id.bImage)).setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				final Intent intent = new Intent();
				intent.setType("image/*");
				intent.setAction(Intent.ACTION_GET_CONTENT);
				intent.putExtra("windowTitle", "Profile Picture");
				try {
					startActivityForResult(intent, INTENT_PICK_PICTURE);
				} catch (final Exception e) {
				}

			}
		});// SETONCLICKLISTENER
		Log.d("------------", "333333333333333333");

		// start loading
		loadUserData();

	}// ONCREATE
	
	// return handler for the "choose image" activity
		@Override
		protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
			Log.d("------------", "66666666666");
			if (requestCode == INTENT_PICK_PICTURE && resultCode != RESULT_CANCELED &&
					(data != null) && (data.getData() != null) && !data.getData().toString().trim().equals("")) {

				showDialog(DIALOG_PROGRESS);
				
				// assign the image
				try {
					Image image = new AndroidImage(data.getData(), getContentResolver());
					
					user.assignImage(image, new Continuation<Boolean>() {
						public void withValue(Boolean result, Exception error) {
							// see if everything went allright
							if(!result) {
								dialogErrorMsg = "profile_image_select_error";
								dismissDialog(DIALOG_PROGRESS);
								showDialog(DIALOG_ERROR);
								return;
							}
							
							// ok, submit the user
							
							// set up a request observer
							RequestControllerObserver observer = new RequestControllerObserver() {

								public void requestControllerDidFail(RequestController aRequestController, Exception anException) {
									dialogErrorMsg = "profile_image_submit_error";
									dismissDialog(DIALOG_PROGRESS);
									showDialog(DIALOG_ERROR);
								}

								public void requestControllerDidReceiveResponse(RequestController aRequestController) {
									loadUserData();
								}
								
							};

							// with our observer, set up the request controller
							UserController userController = new  UserController(observer);
							
							// pass the user into the controller
							userController.setUser(user);
							
							// submit our changes
							userController.submitUser();
							
						}
					});
				} catch (FileNotFoundException e1) {
					dialogErrorMsg = "profile_image_select_error";
					dismissDialog(DIALOG_PROGRESS);
					showDialog(DIALOG_ERROR);
				}
				
				
			}
			
		}
	
	
	// loads user's data
	private void loadUserData() {
		Log.d("------------", "444444444444444");
		
		RequestControllerObserver observer = new RequestControllerObserver() {

			public void requestControllerDidReceiveResponse(
					RequestController requestController) {

				UserController userController = (UserController) requestController;
				dismissDialog(DIALOG_PROGRESS);

				User user = userController.getUser();

				// insert valuser into textfields
				usernameText.setText(user.getLogin());
				emailText.setText(user.getEmailAddress());

				// load the profile picture
				final ImageView profilePic = (ImageView) findViewById(R.id.bImage);

				// IMAGE DECODING START
				(new AsyncTask<String, Void, Bitmap>() {

					@Override
					protected Bitmap doInBackground(String... params) {
						Bitmap result = null;
						try {
							URLConnection urlConnection = new URL(params[0])
									.openConnection();
							// use caching
							urlConnection.setUseCaches(true);
							result = BitmapFactory.decodeStream(urlConnection
									.getInputStream());
						} catch (Exception e) {
						}
						return result;
					}

					protected void onPreExecute() {
						profilePic.setImageResource(R.drawable.ic_launcher);
					}

					protected void onPostExecute(Bitmap result) {
						if (result != null) {
							profilePic.setImageBitmap(result);
						} else {
							profilePic
									.setImageResource(R.drawable.sl_icon_user);
						}
					}
				}).execute(user.getImageUrl());
				// IMAGE DECODING END

			}

			public void requestControllerDidFail(RequestController arg0,
					Exception arg1) {
				dismissDialog(DIALOG_ERROR);
				dialogErrorMsg = "loading profile error";
				showDialog(DIALOG_ERROR);

			}

		};// REQUESTCONTROLLEROBSERVER
		
		UserController userController = new UserController(observer);
		showDialog(DIALOG_PROGRESS);
		userController.loadUser();
		
		Log.d("------------", "55555555555555");
		
	}//loaduserData

	// handler to create our dialogs
	@Override
	protected Dialog onCreateDialog(final int id) {
		Log.d("------------", "6666666666666666666AAAAAA");
		switch (id) {
			
			case DIALOG_PROGRESS :
				return ProgressDialog.show(ProfileActivity.this, "",
						"LOADING STRING");
			case DIALOG_ERROR :
				return (new AlertDialog.Builder(this))
						.setPositiveButton("too badd", null).setMessage("")
						.create();
			case DIALOG_SUCCESS :
				return (new AlertDialog.Builder(this))
						.setTitle("SCoreLoop String")
						.setIcon(
								getResources().getDrawable(
										R.drawable.ic_launcher))
						.setPositiveButton("Awesome String", null)
						.setMessage("").create();
		}
		Log.d("------------", "6666BBBBBBBBBBBBBBBBBBBBBB");
		return null;
	}

	// handler to update success & error dialog with corresponding message
	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		Log.d("------------", "666666CCCCCCCCCCCCCCCC");
		switch (id) {
			case DIALOG_ERROR :
				AlertDialog errorDialog = (AlertDialog) dialog;
				errorDialog.setMessage(dialogErrorMsg);
				break;
			case DIALOG_SUCCESS :
				AlertDialog successDialog = (AlertDialog) dialog;
				successDialog.setMessage(dialogSuccessMsg);
				break;
		}
	}

}
